pub mod handle_stream;

use std::{
    sync::{mpsc, Arc, Mutex},
    thread,
};

/// 自定义线程池
pub struct ThreadPool {
    /// 持有线程池，一个处理器数组
    workers: Vec<Worker>,
    /// 发送任务至worker
    sender: Option<mpsc::Sender<Job>>,
}

/// 接收任务处理者，用于分离创建线程和执行任务作为两者的桥梁，即工作线程
struct Worker {
    /// 编号
    id: usize,
    /// oinHandle的泛型为返回值，因此为()
    thread: Option<thread::JoinHandle<()>>,
}

/// 闭包约束的别名：任务
type Job = Box<dyn FnOnce() + Send + 'static>;

impl ThreadPool {
    /// 创建池，输入线程数量
    ///
    /// `size` - The size is the number of threads in the pool.
    ///
    /// # Panics
    ///
    /// The `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);
        // 发送与接收
        let (sender, receiver) = mpsc::channel();
        // 共享且互斥（实现多个接收者，本质只有一个，借用互斥锁）
        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool {
            workers,
            sender: Some(sender),
        }
    }

    /// 执行一次闭包任务.
    ///
    ///
    /// **FnOnce**: 闭包作为任务只需被线程执行一次即可，无参无返回  
    /// **Send**: 闭包需要从一个线程传递到另一个线程  
    /// **'static**: 并不知道线程需要多久时间来执行该任务  
    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);
        self.sender.as_ref().unwrap().send(job).unwrap(); // 发送闭包
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        // 立刻停止发送器
        drop(self.sender.take());

        // 终止并回收每个worker
        for worker in self.workers.iter_mut() {
            println!("Shutting down worker {}", worker.id);

            // 尝试拿走所有权
            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap(); // 等待其执行完毕
            }
        }
    }
}

impl Worker {
    /// 创建一个任务处理器
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        // 线程需要用循环，并将接收器转入
        let thread = thread::spawn(move || loop {
            let message = receiver.lock().unwrap().recv(); // 获取锁并尝试获取Job

            match message {
                Ok(job) => {
                    println!("Worker {id} got a job; executing.");
                    job(); // 调用闭包
                }
                Err(_) => {
                    println!("Worker {id} disconnected; shutting down.");
                    break; // 出循环结束线程
                }
            }
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}
